/**
 * @fileOverview The "table" plugin.
 */
VED.plugins.add( 'table', {
   requires: 'dialog',
   lang: 'en,ru', // %REMOVE_LINE_CORE%
   icons: 'table', // %REMOVE_LINE_CORE%
   init: function( editor ) {
      if ( editor.blockless )
         return;

      var table = VED.plugins.table,
         lang = editor.lang.table;

      editor.addCommand( 'table', new VED.dialogCommand( 'table', { context: 'table' } ) );

      function createDef( def ) {
         return VED.tools.extend( def || {}, {
            contextSensitive: 1,
            refresh: function( editor, path ) {
               this.setState( path.contains( 'table', 1 ) ? VED.TRISTATE_OFF : VED.TRISTATE_DISABLED );
            }
         });
      }

      editor.addCommand( 'tableProperties', new VED.dialogCommand( 'tableProperties', createDef() ) );
      editor.addCommand( 'tableDelete', createDef({
         exec: function( editor ) {
            var path = editor.elementPath(),
               table = path.contains( 'table', 1 );

            if ( !table )
               return;

            // If the table's parent has only one child remove it as well (unless it's the body or a table cell) (#5416, #6289)
            var parent = table.getParent();
            if ( parent.getChildCount() == 1 && !parent.is( 'body', 'td', 'th' ) )
               table = parent;

            var range = editor.createRange();
            range.moveToPosition( table, VED.POSITION_BEFORE_START );
            table.remove();
            range.select();
         }
      }));

      editor.ui.addButton && editor.ui.addButton( 'Table', {
         label: lang.toolbar,
         command: 'table',
         toolbar: 'insert,30'
      });

      VED.dialog.add( 'table', this.path + 'dialogs/table.js' );
      VED.dialog.add( 'tableProperties', this.path + 'dialogs/table.js' );

      // If the "menu" plugin is loaded, register the menu items.
      if ( editor.addMenuItems ) {
         editor.addMenuItems({
            table: {
               label: lang.menu,
               command: 'tableProperties',
               group: 'table',
               order: 5
            },

            tabledelete: {
               label: lang.deleteTable,
               command: 'tableDelete',
               group: 'table',
               order: 1
            }
         });
      }

      editor.on( 'doubleclick', function( evt ) {
         var element = evt.data.element;

         if ( element.is( 'table' ) )
            evt.data.dialog = 'tableProperties';
      });

      // If the "contextmenu" plugin is loaded, register the listeners.
      if ( editor.contextMenu ) {
         editor.contextMenu.addListener( function() {
            // menu item state is resolved on commands.
            return {
               tabledelete: VED.TRISTATE_OFF,
               table: VED.TRISTATE_OFF
            };
         });
      }
   }
});






